import Taro, { useDidShow } from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect } from 'react';
import { View, Text, Button, Image } from '@tarojs/components';


import './index.scss';
import ScoreStar from '../../components/scoreStar';
import ImageLoader from '../../components/ImageLoader';
import { useAppContext } from '../../contexts/AppContext';
import { CoachCenterData, CoachReservationData, CoachStatData } from '../../types/coach';
import { getCoachCenterOverviewApi, getCoachReservationsApi, getCoachStatsApi, confirmNewStudentApi, getWechatPayParamsApi } from '../../api/coachApi';



/**
 * 教练中心页面组件
 * 展示教练信息、功能菜单和学习进度
 */
const CoachCenterPage: React.FC = () => {
  // 状态管理
  const { userInfo } = useAppContext();
  const [coachCenterData, setCoachCenterData] = useState<CoachCenterData | null>(null);
  const [reservationData, setReservationData] = useState<CoachReservationData | null>(null);
  const [statData, setStatData] = useState<CoachStatData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 页面每次显示时重新获取数据
  useDidShow(() => {
    loadAllData();
  });

  // 加载所有数据
  const loadAllData = async () => {
    try {
      setIsLoading(true);
      console.log('加载教练中心数据');
      // 并行加载所有数据
      await Promise.all([
        getCoachCenterOverviewApi(),
        getCoachReservationsApi(),
        getCoachStatsApi()
      ]).then(([centerOverviewResponse, reservationResponse, statResponse]) => {
        // 更新状态
        if (centerOverviewResponse.code === 200) {
          setCoachCenterData(centerOverviewResponse.data);
        }
        
        if (reservationResponse.code === 200) {
          setReservationData(reservationResponse.data);
        }
        
        if (statResponse.code === 200) {
          setStatData(statResponse.data);
        }
      });
    } catch (error) {
      console.error('加载教练中心数据失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 确认新学员
  const handleConfirmStudent = async () => {
    try {
      // 从界面上获取第一个待确认的学员ID
      // 注意：实际实现中可能需要从coachCenterData或其他状态中获取真实的学员ID
      // 这里暂时保留接口调用，但会在无ID时提示用户
      if (!coachCenterData || coachCenterData.unconfirmedStudents === 0) {
        Taro.showToast({
          title: '暂无待确认学员',
          icon: 'none'
        });
        return;
      }
      
      // 提示用户选择具体学员进行确认
      Taro.showToast({
        title: '请进入学员列表选择具体学员进行确认',
        icon: 'none',
        duration: 2000
      });
      
      // 跳转到学员列表页面
      Taro.navigateTo({ url: '/pages/student-list/index' });
      
    } catch (error) {
      console.error('确认学员失败:', error);
      Taro.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  };

  // 续费会员
  const handleRenewMembership = () => {
    // 跳转到会员续费页面
    Taro.navigateTo({
      url: '/pages/member-pay/index'
    });
  };

  // 处理微信支付
  const handleWechatPay = async (amount: number, desc: string) => {
    try {
      // 显示加载提示
      Taro.showLoading({ title: '获取支付信息中...' });
      
      // 调用后端API获取支付参数
      const response = await getWechatPayParamsApi(amount, desc);
      
      // 隐藏加载提示
      Taro.hideLoading();
      
      // 检查响应状态
      if (response.code === 0 && response.data) {
        const payParams = {
          timeStamp: response.data.timeStamp,
          nonceStr: response.data.nonceStr,
          package: response.data.package,
          signType: response.data.signType,
          paySign: response.data.paySign
        };
        
        // 调用微信支付
        const payResult = await Taro.requestPayment({
          ...payParams,
          success: (res) => {
            console.log('支付成功', res);
            Taro.showToast({
              title: '支付成功',
              icon: 'success'
            });
            // 支付成功后可以刷新页面数据
            loadAllData();
          },
          fail: (err) => {
            console.log('支付失败', err);
            // 判断是否是用户取消支付
            if (err.errMsg && err.errMsg.indexOf('cancel') > -1) {
              Taro.showToast({
                title: '支付已取消',
                icon: 'none'
              });
            } else {
              Taro.showToast({
                title: '支付失败，请重试',
                icon: 'none'
              });
            }
          }
        });
      } else {
        // 处理API返回错误
        Taro.showToast({
          title: response.message || '获取支付参数失败',
          icon: 'none'
        });
      }
      
    } catch (error) {
      console.error('支付请求失败:', error);
      Taro.hideLoading();
      Taro.showToast({
        title: '支付请求失败，请重试',
        icon: 'none'
      });
    }
  };

  // 设置按钮点击处理
  const handleSettingsClick = () => {
    console.log('Settings button clicked!');
    Taro.navigateTo({
      url: '/pages/coach-setting/index'
    });
  };

  /**
   * 余额充值功能
   */
  const handleRecharge = () => {
    Taro.navigateTo({
      url: '/pages/balance-recharge/index'
    });
  };

  /**
   * 扫码验券功能
   * 1. 申请相机权限
   * 2. 打开相机扫描二维码
   * 3. 处理扫描结果
   */
  const handleScanCoupon = async () => {
    try {
      // 首先检查是否有相机权限
      const settingResult = await Taro.getSetting();
      
      if (!settingResult.authSetting['scope.camera']) {
        // 如果没有权限，先尝试向用户申请
        try {
          await Taro.authorize({
            scope: 'scope.camera'
          });
          // 授权成功，继续扫码
          await performScanCode();
        } catch (authError: any) {
          // 授权失败，提示用户去设置页面开启权限
          if (authError.errMsg && authError.errMsg.indexOf('auth deny') > -1) {
            Taro.showModal({
              title: '权限提示',
              content: '需要相机权限才能扫码，请前往设置开启',
              confirmText: '去设置',
              cancelText: '取消',
              success: (res) => {
                if (res.confirm) {
                  // 跳转到设置页面
                  Taro.openSetting({
                    success: (settingRes) => {
                      // 用户从设置页面返回后，再次检查权限
                      if (settingRes.authSetting['scope.camera']) {
                        // 用户在设置中开启了权限，直接执行扫码
                        performScanCode();
                      } else {
                        Taro.showToast({
                          title: '相机权限未开启，无法扫码',
                          icon: 'none'
                        });
                      }
                    }
                  });
                }
              }
            });
          } else {
            console.error('权限申请过程中出错:', authError);
            Taro.showToast({
              title: '权限申请失败，请重试',
              icon: 'none'
            });
          }
        }
      } else {
        // 已经有权限，直接扫码
        await performScanCode();
      }
    } catch (error) {
      console.error('检查权限过程中出错:', error);
      Taro.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  };

  /**
   * 执行扫码操作
   */
  const performScanCode = async () => {
    try {
      const scanResult = await Taro.scanCode({
        onlyFromCamera: true,
        scanType: ['qrCode'],
        success: (res) => {
          console.log('扫码成功:', res);
          // 处理扫码结果
          processScanResult(res.result);
        },
        fail: (err) => {
          console.error('扫码失败:', err);
          // 判断是否是用户取消扫码
          if (err.errMsg && err.errMsg.indexOf('cancel') > -1) {
            Taro.showToast({
              title: '扫码已取消',
              icon: 'none'
            });
          } else {
            Taro.showToast({
              title: '扫码失败，请重试',
              icon: 'none'
            });
          }
        }
      });

      // 处理扫码结果
      if (scanResult && scanResult.result) {
        processScanResult(scanResult.result);
      }
    } catch (error) {
      console.error('扫码过程中出错:', error);
      Taro.showToast({
        title: '扫码失败，请重试',
        icon: 'none'
      });
    }
  };

  /**
   * 处理扫码结果
   * @param qrCodeContent 二维码内容
   */
  const processScanResult = (qrCodeContent: string) => {
    try {
      // 显示扫码结果
      Taro.showToast({
        title: '扫码成功',
        icon: 'success'
      });

      // 解析二维码内容
      // 假设二维码内容是JSON字符串或URL参数
      console.log('二维码内容:', qrCodeContent);
      
      // 这里可以根据实际业务需求解析和处理二维码内容
      // 例如，验证优惠券、处理订单等
      
      // 显示解析结果给用户
      Taro.showModal({
        title: '扫码结果',
        content: `二维码内容:\n${qrCodeContent.substring(0, 50)}${qrCodeContent.length > 50 ? '...' : ''}`,
        showCancel: false
      });
    } catch (error) {
      console.error('处理扫码结果失败:', error);
      Taro.showToast({
        title: '解析二维码内容失败',
        icon: 'none'
      });
    }
  };

  // 功能菜单点击
  const handleMenuClick = (menuName: string) => {
    Taro.showToast({
      title: `点击了${menuName}`,
      icon: 'none'
    });
    // 根据不同的菜单项跳转到对应的页面
    switch (menuName) {
      case '客资管理':
        Taro.navigateTo({ url: '/pages/client-management/index' });
        break;
      case '学员名单':
        Taro.navigateTo({ url: '/pages/student-list/index' });
        break;
      case '星级管理':
        Taro.navigateTo({ url: '/pages/star-management/index' });
        break;
      case '推广':
        Taro.navigateTo({ url: '/pages/promotion/index' });
        break;
      case '评价':
        Taro.navigateTo({ url: '/pages/coach-evaluation/index' });
        break;
      case '参加活动':
        Taro.navigateTo({ url: '/pages/activities/index' });
        break;
      // case '直播':
      //   Taro.navigateTo({ url: '/pages/live/index' });
      //   break;
      case '日志':
        Taro.navigateTo({ url: '/pages/log/index' });
        break;
      case '点击率':
        Taro.navigateTo({ url: '/pages/click-rate/index' });
        break;
      case '扫码验券':
        handleScanCoupon();
        break;
      default:
        break;
    }
  };

  // 功能菜单配置
  const menuItems = [
    { text: '客资管理', icon: 'mail', color: '#1890ff' },
    { text: '学员名单', icon: 'person', color: '#52c41a' },
    { text: '星级管理', icon: 'rate-review', color: '#faad14' },
    { text: '推广', icon: 'volume-up', color: '#ff4d4f' },
    { text: '评价', icon: 'thumb-up', color: 'rgb(90,177,255)' },
    { text: '参加活动', icon: 'view-comfy', color: '#fa8c16' },
    // { text: '直播', icon: 'videocam', color: '#eb2f96' },
    { text: '日志', icon: 'edit', color: '#52c41a' },
    { text: '点击率', icon: 'bubble-chart', color: '#13c2c2' },
    { text: '扫码验券', icon: 'settings-overscan', color: '#faad14' }
  ];

  // 渲染功能菜单项
  const renderMenuItem = (item: { text: string, icon: string, color: string }) => {
    return (
      <View 
        className="menu-item" 
        onClick={() => handleMenuClick(item.text)}
      >
        <View className="menu-icon-container">
          <MaterialIcons name={item.icon} color={item.color} size={32} />
        </View>
        <Text className="menu-text">{item.text}</Text>
      </View>
    );
  };

  if (isLoading) {
    return (
      <View className="coach-center-page">
        <Text>加载中...</Text>
      </View>
    );
  }

  return (
    <>
      <View className="coach-center-page">
        {/* 头部教练信息卡片 */}
        <View className="coach-header-card">
          <View className="coach-info">
            <View style={{ display: 'flex', alignItems: 'center' }}>
              <ImageLoader
                className="coach-center-avatar" 
                src={userInfo?.avatar || ""} 
                mode="aspectFill"
              />
              <View className="coach-details">
                <View className="coach-name">
                  {userInfo?.username || '未知'}
                </View>
                <View className="coach-base">
                  {coachCenterData?.coachInfo?.school || '未知'}
                </View>
                <View className="coach-score">
                  <ScoreStar score={coachCenterData?.coachInfo?.score || 5} size={16}/>
                </View>

                <View className="membership-info">
                  <Text className="membership-expiry">
                    {coachCenterData?.membershipExpiry || '未知'}会员过期
                  </Text>
                  <View className="renew-btn" onClick={handleRenewMembership}>
                    立即续费
                  </View>
                </View>
              </View>
            </View>
            <View className="header-actions">
              <MaterialIcons 
                name="settings" 
                color="#666" 
                size={28} 
                onClick={handleSettingsClick} 
              />
            </View>
          </View>
        </View>

        {/* 预约统计区域 */}
        <View className="reservation-stats">
          <View className="reservation-item">
              <Text className="reservation-title">面签预约</Text>
              <Text className="reservation-count">{reservationData?.interviewCount || 0}人</Text>
            </View>
            <View className="reservation-item">
              <Text className="reservation-title">科二预约</Text>
              <Text className="reservation-count">{reservationData?.subjectTwoCount || 0}人</Text>
            </View>
            <View className="reservation-item">
              <Text className="reservation-title">科三预约</Text>
              <Text className="reservation-count">{reservationData?.subjectThreeCount || 0}人</Text>
            </View>
        </View>

        {/* 浏览统计区域 */}
        <View className="browse-stats">
          <View className="stat-row">
            <View className="stat-item">
              <Text className="stat-title">浏览人数</Text>
              <View className="stat-count-with-arrow">
                  <Text className="stat-count">{statData?.views || 0}</Text>
                  <View className="comparison-arrow">
                    {statData && statData.views !== undefined && statData.yesterdayViews !== undefined && 
                      parseInt(statData.views.toString()) > parseInt(statData.yesterdayViews.toString()) ? (
                      <MaterialIcons name="arrow-upward" color='#ff6b6b' size={20} />
                    ) : statData && statData.views !== undefined && statData.yesterdayViews !== undefined && 
                      parseInt(statData.views.toString()) < parseInt(statData.yesterdayViews.toString()) ? (
                      <MaterialIcons name="arrow-downward" color='#53cc85' size={20} />
                    ) : null}
                  </View>
                </View>
                <Text className="stat-yesterday">昨日 {statData?.yesterdayViews || 0}</Text>
            </View>
            <View className="stat-item">
              <Text className="stat-title">咨询人数</Text>
              <View className="stat-count-with-arrow">
                  <Text className="stat-count">{statData?.consultationCount || 0}</Text>
                  <View className="comparison-arrow">
                    {statData && statData.consultationCount !== undefined && statData.yesterdayConsultationCount !== undefined && 
                      parseInt(statData.consultationCount.toString()) > parseInt(statData.yesterdayConsultationCount.toString()) ? (
                      <MaterialIcons name="arrow-upward" color='#ff6b6b' size={20} />
                    ) : statData && statData.consultationCount !== undefined && statData.yesterdayConsultationCount !== undefined && 
                      parseInt(statData.consultationCount.toString()) < parseInt(statData.yesterdayConsultationCount.toString()) ? (
                      <MaterialIcons name="arrow-downward" color='#53cc85' size={20} />
                    ) : null}
                  </View>
                </View>
                <Text className="stat-yesterday">昨日 {statData?.yesterdayConsultationCount || 0}</Text>
            </View>
            <View className="stat-item">
              <Text className="stat-title">成交人数</Text>
              <View className="stat-count-with-arrow">
                  <Text className="stat-count">{statData?.dealCount || 0}</Text>
                  <View className="comparison-arrow">
                    {statData && statData.dealCount !== undefined && statData.yesterdayDealCount !== undefined && 
                      parseInt(statData.dealCount.toString()) > parseInt(statData.yesterdayDealCount.toString()) ? (
                      <MaterialIcons name="arrow-upward" color='#ff6b6b' size={20} />
                    ) : statData && statData.dealCount !== undefined && statData.yesterdayDealCount !== undefined && 
                      parseInt(statData.dealCount.toString()) < parseInt(statData.yesterdayDealCount.toString()) ? (
                      <MaterialIcons name="arrow-downward" color='#53cc85' size={20} />
                    ) : null}
                  </View>
                </View>
                <Text className="stat-yesterday">昨日 {statData?.yesterdayDealCount || 0}</Text>
            </View>
          </View>
        </View>

        {/* 排名区域 */}
        <View className="rankings">
          <Text className="rank-title">排名信息</Text>
          <View className="rank-item">
              <Text className="rank-name">基地排名</Text>
              <Text className="rank-value">第{statData?.baseRank || 0}名</Text>
            </View>
            <View className="rank-item">
              <Text className="rank-name">上海排名</Text>
              <Text className="rank-value">第{statData?.cityRank || 0}名</Text>
            </View>
            <View className="rank-item">
              <Text className="rank-name">全国排名</Text>
              <Text className="rank-value">第{statData?.nationalRank || 0}名</Text>
            </View>
        </View>

        {/* 新学员提醒和余额提醒合并区域 */}
        <View className="student-balance-alert">
          <View className="alert-left">
            <View className="new-student-section">
              <Image 
                src="" 
                style={{ width: '40px', height: '40px', marginRight: '8px' }} 
              />
              <View className="alert-content">
                <Text className="alert-text">
                  您有{coachCenterData?.unconfirmedStudents || 0}个新的学员请确认
                </Text>
              </View>
            </View>
            <View>
              <Text className="alert-text">建议 请确保余额足够佣金扣款</Text>
            </View>
          </View>
          <View className="balance-section">
            <Text>余额</Text>
            <Text className="balance-amount">{coachCenterData?.balance || 0} 元</Text>
            <Button className="recharge-btn" onClick={handleRecharge}>
              充值
            </Button>
          </View>
        </View>

        {/* 功能菜单 */}
        <View className="function-menu">
          {menuItems.map((item, index) => renderMenuItem(item))}
        </View>
      </View>
    </>
  );
};

export default CoachCenterPage;